package logger

import (
	"base-gin/app/config"
	"fmt"
	"github.com/natefinch/lumberjack"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"os"
)

func init() {
	writeIo := buildWriteIo()
	enCode := buildEncode()
	logLevel := buildLogLevel()

	var core zapcore.Core
	//如果是开发模式则多输出一份日志到终端
	if config.App.Mode == "dev" {
		// 进入开发模式，日志输出到终端
		consoleEncoder := zapcore.NewConsoleEncoder(enCode)
		core = zapcore.NewTee(
			zapcore.NewCore(zapcore.NewConsoleEncoder(enCode), writeIo, logLevel),
			zapcore.NewCore(consoleEncoder, zapcore.Lock(os.Stdout), zapcore.DebugLevel), //开发模式控制台输出debug
		)
	} else {
		core = zapcore.NewCore(zapcore.NewConsoleEncoder(enCode), writeIo, logLevel)
	}

	logger := zap.New(core, zap.AddCaller())
	zap.ReplaceGlobals(logger)
}

// 构建日志级别
func buildLogLevel() (logLeval *zapcore.Level) {
	logLeval = new(zapcore.Level)
	//设置为配置中的日志级别
	err := logLeval.UnmarshalText([]byte(config.LogConfig.Level))
	if err != nil {
		panic(fmt.Errorf("日志级别设置异常: err:%s \n", err))
	}
	return logLeval
}

// 构建日志格式
func buildEncode() zapcore.EncoderConfig {
	encoderConfig := zap.NewProductionEncoderConfig()                             //获取默认格式配置
	encoderConfig.EncodeTime = zapcore.TimeEncoderOfLayout("2006-01-02 15:04:05") //修改时间显示方式
	encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder                       //日导显示大写级别
	encoderConfig.EncodeCaller = zapcore.FullCallerEncoder                        //调用方法全路径
	encoderConfig.EncodeName = zapcore.FullNameEncoder
	//encoderConfig.EncodeDuration = zapcore.SecondsDurationEncoder //没搞懂
	//encoderConfig.EncodeCaller = zapcore.ShortCallerEncoder       //没搞懂
	//return zapcore.NewJSONEncoder(encoderConfig) //这种为构建成json格式
	return encoderConfig
	//return zapcore.NewConsoleEncoder(encoderConfig)
}

// 构建日志写入流
func buildWriteIo() zapcore.WriteSyncer {
	lumberJackLogger := &lumberjack.Logger{
		Filename:   config.LogConfig.Filename,   //文件名
		MaxSize:    config.LogConfig.MaxSize,    //文件最大小
		MaxBackups: config.LogConfig.MaxBackups, //文件最多个数
		MaxAge:     config.LogConfig.MaxAge,     //保留旧文件最大天数
	}
	return zapcore.AddSync(lumberJackLogger)
}
